<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/13
 * Time: 12:07
 */

namespace common\service;

use backend\modules\kwx\ApiService;
use backend\modules\kwx\models\Baseorders;
use backend\modules\kwx\models\Baseproducts;
use backend\modules\kwx\models\DurationPermission;
use backend\models\PackItem;
use backend\models\PackPlayer;
use backend\models\PlayerCurrencyRecordTbl;
use backend\models\PlayerTbl;
use backend\models\RolePlayerInfo;
use backend\models\SystemMail;
use Yii;

class PayService
{
    public function OrderRecharge($orderId)
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $order = Baseorders::findOne(['OrderId' => $orderId]);
            if ($order->PayStatus > 0){
                return ['statusCode' => 300, 'message' => '此订单已关闭'];
            }
            $userId = $order->UserId;
            $product = Baseproducts::findOne(['ProductId' => $order->ProductId]);
            $playTbl = PlayerTbl::findOne(['PlayerID' => $userId]);
            $coin_dia_num = $product->NumCount;
            $classId = $product->ClassId;
            if ($classId < 2) {//金币和钻石充值
                if ($classId === 0){//钻石充值
                    $typestate = 'Diamond';
                    $p_coin = $playTbl->Diamond;
                }elseif ($classId === 1){//金币充值
                    $typestate = 'GoldCoin';
                    $p_coin = $playTbl->GoldCoin;
                }else{
                    $typestate = 'GoldCoin';
                    $p_coin = $playTbl->GoldCoin;
                }
                $nowNum = $p_coin + $coin_dia_num;
                $rechargeTime = $playTbl->RechargeTimes;
//          首次充值金币或者钻石时，赠送10个钻石,[特价商品除外]
                $productId = $order->ProductId;
                if (empty($rechargeTime) && ($productId < 2000)){
                    if ($classId === 0){//钻石充值
                        $nowNum = $nowNum + 10;
                    }elseif($classId === 1){//金币充值
                        $p_coin = $playTbl->Diamond;
                        $goldNum = $p_coin + 10;
                        PlayerTbl::updateAll(['Diamond' => $goldNum],'PlayerID = :PlayerID',[':PlayerID'=>$userId]);
                    }
                    $stat = self::writeRecord($orderId);
                    if ($stat == false){
                        return ['statusCode' => 300, 'message' => '赠送记录写入失败'];
                    }
                }
                //代理提点分成---【只对购买钻石类型进行分成】
                if (empty($classId)){
                    $proservice = new ApiService();
                    $result = $proservice->buildProcedure($orderId);
                    if ($result['status'] <> 1){
                        return ['statusCode' => 300, 'message' => '代理分成失败'];
                    }
                }
                //开启额外赠送
                $extracount = 0;
                $extrascale = 0;
                if ($product->ExtraScale > 0){//额外比例
                    $pecal = $product->ExtraScale;
                    $ncont = $product->NumCount;
                    $extrascale = $ncont * $pecal;
                    $status = self::writeExtraRecord($orderId, $extrascale, 1);
                    if ($status == false){
                        return ['statusCode' => 300, 'message' => '额外比例赠送记录写入失败'];
                    }
                }
                if ($product->ExtraCount > 0){//额外个数
                    $extracount = $product->ExtraCount;
                    $status = self::writeExtraRecord($orderId, $extracount, 2);
                    if ($status == false){
                        return ['statusCode' => 200, 'message' => '额外个数赠送记录写入失败'];
                    }
                }
                $nowNum = $nowNum + $extrascale + $extracount;
                PlayerTbl::updateAll([$typestate => $nowNum, 'RechargeTimes' => $rechargeTime + 1],'PlayerID = :PlayerID',[':PlayerID'=>$userId]);
                Baseorders::updateAll(['PayStatus'=>1, 'PayDate'=>date('Y-m-d H:i:s',time())], 'OrderId = :OrderId', [':OrderId' => $orderId]);
                self::writeRecord($orderId);
            }elseif ($classId == 2){
                $packitemid = $product->PackId;
                $amount = $order->NumCount;
                $packitem = PackItem::findOne(['id'=>$packitemid]);
                if ($packitem->classify_id == 2){//id=2 为纪念币类型
                    //写入玩家道具记录表pack_player [同类别的累加]
                    $packplayer = PackPlayer::findOne(['item_id'=>$packitemid ,'user_id' => $userId]);
                    $pamount = 0;
                    if ($packplayer){
                        $pamount = $packplayer->amount;
                        $packplayer->amount = $amount + $pamount;
                    }else{
                        $packplayer = new PackPlayer();
                        $packplayer->user_id = $userId;
                        $packplayer->item_id = $packitemid;
                        $packplayer->amount = $amount;
                    }
                    $packplayer->save();
                }elseif (($packitem->classify_id == 6) || ($packitem->classify_id == 7)){//id=6/7 为普通月卡/至尊月卡类型
                    $permission = DurationPermission::findOne(['user_id'=>$userId]);
                    if ($permission){
                        if ($packitem->classify_id == 6){//id=6 为普通月卡(30天共计720小时)
                            $end_time = $permission->ordinary_end_time;
                            if ($end_time < time()){
                                $permission->ordinary_start_time = time();
                                $permission->ordinary_end_time = time() + 3600*720;
                            }else{
                                $permission->ordinary_end_time = $end_time + 3600*720;
                            }
                        }
                        if ($packitem->classify_id == 7){//id=7 为至尊月卡
                            $end_time = $permission->super_end_time;
                            if ($end_time < time()){
                                $permission->super_start_time = time();
                                $permission->super_end_time = time() + 3600*720;
                            }else{
                                $permission->super_end_time = $end_time + 3600*720;
                            }
                        }
                    }else{
                        $permission = new DurationPermission();
                        $permission->user_id = $userId;
                        if ($packitem->classify_id == 6){//id=6 为普通月卡
                            $permission->ordinary_start_time = time();
                            $permission->ordinary_end_time = time() + 3600*720;
                        }
                        if ($packitem->classify_id == 7){//id=7 为至尊月卡
                            $permission->super_start_time = time();
                            $permission->super_end_time = time() + 3600*720;
                        }
                    }
                    $permission->save();
                    //至尊月卡赠送雅静角色(角色id=20002)
                    if ($packitem->classify_id == 7){//至尊月卡
                        $roleplayer = RolePlayerInfo::findOne(['role_id'=>20002,'playerid'=>$userId]);
                        if (!$roleplayer){
                            $roleplayer = new RolePlayerInfo();
                            $roleplayer->playerid = $userId;
                            $roleplayer->role_id = 20002;
                            $roleplayer->effective_time = 30;
                            $roleplayer->active_time = time();
                            $roleplayer->role_status = 1;
                        }else{
                            $Id = $roleplayer->ID;
                            $effective_time = $roleplayer->effective_time;
                            $active_time = $roleplayer->active_time;
                            if ($effective_time < 0){//存在永久时间
                                $roleplayer->active_time = time();
                            }else{
                                $newTime = $active_time + $effective_time * 24 * 3600;
                                if ($newTime <= time()){//过期
                                    RolePlayerInfo::deleteAll(['ID'=>$Id]);
                                    $roleplayer = new RolePlayerInfo();
                                    $roleplayer->playerid = $userId;
                                    $roleplayer->role_id = 20002;
                                    $roleplayer->effective_time = 30;
                                    $roleplayer->active_time = time();
                                    $roleplayer->role_status = 1;
                                }else{
                                    $roleplayer->effective_time = $effective_time + 30;
                                }
                            }
                        }
                        $roleplayer->save();
                        //购买成功后首次发送10个钻石和10万金币
                        $sysemail = new SystemMail();
                        $sysemail->PlayerID = $userId;
                        $sysemail->MailTab = '月卡奖励';
                        $sysemail->MailTabType = 1;
                        $sysemail->MailTitle = '尊享月卡奖励发放';
                        $sysemail->Sender = '百游卡五星系统';
                        $sysemail->MailInfo = '尊贵的尊享月卡用户，今日为您奉上10钻石、10万金币，望您笑纳。尊享月卡附送的角色（雅婧）30天已激活，您可以随时到外观界面使用。';
                        $sysemail->AttachmentGoldcoin = 100000;
                        $sysemail->AttachmentDiamond = 10;
                        $sysemail->MailTime = time();
                        $sysemail->save();
                    }
                    if ($packitem->classify_id == 6){//理财月卡
                        //购买成功后首次发送2个钻石和2万金币
                        $sysemail = new SystemMail();
                        $sysemail->PlayerID = $userId;
                        $sysemail->MailTab = '月卡奖励';
                        $sysemail->MailTabType = 1;
                        $sysemail->MailTitle = '理财月卡奖励发放';
                        $sysemail->Sender = '百游卡五星系统';
                        $sysemail->MailInfo = '尊贵的理财月卡用户，今日为您奉上2钻石、2万金币，望您笑纳。';
                        $sysemail->AttachmentGoldcoin = 20000;
                        $sysemail->AttachmentDiamond = 2;
                        $sysemail->MailTime = time();
                        $sysemail->save();
                    }
                }
                //首次充值金币或者钻石时，赠送10个钻石,[特价商品除外]
                $productId = $order->ProductId;
                $rechargeTime = $playTbl->RechargeTimes;
                if (empty($rechargeTime) && ($productId < 2000)){
                    $p_coin = $playTbl->Diamond;
                    $goldNum = $p_coin + 10;
                    PlayerTbl::updateAll(['Diamond' => $goldNum],'PlayerID = :PlayerID',[':PlayerID'=>$userId]);
                    $stat = self::writeRecord($orderId);
                    if ($stat == false){
                        return ['statusCode' => 300, 'message' => '手动充值失败'];
                    }
                }
                PlayerTbl::updateAll(['RechargeTimes' => $rechargeTime+1],'PlayerID = :PlayerID',[':PlayerID'=>$userId]);
                //写入购买记录
                $playcurrency = new PlayerCurrencyRecordTbl();
                $playcurrency->playerId = $userId;
                $playcurrency->typeId = 3;//道具类型为3
                $playcurrency->Currency = $amount;
                $playcurrency->beforeCurrency = empty($pamount) ? 0 : $pamount;
                $playcurrency->afterCurrency = empty($pamount) ? $amount : ($amount + $pamount);
                $playcurrency->Comments = '购买背包道具：'.$packitem['name'].',数量：'.$amount;
                $playcurrency->recordDate = date('Y-m-d H:i:s', time());
                $playcurrency->AddrIp = PubService::real_ip();
                $playcurrency->adminId = 1;
                $playcurrency->save();
                //支付成功 修改订单状态
                $order->PayStatus = 1;
                $order->PayDate = date('Y-m-d H:i:s', time());
                $order->save();
            }
            $transaction->commit();
            return ['statusCode' => 200, 'message' => '手动充值成功'];
        } catch (\Exception $e) {
            $transaction->rollBack();
            return ['statusCode' => 300, 'message' => '手动充值失败'];
        }
    }

    /**
     * @param $orderId
     * @return bool
     * 首充和购买记录写入[首充金币和钻石均赠送10个钻石]
     */
    public function writeRecord($orderId)
    {
        //写入充值赠送钻石记录
        $order = Baseorders::findOne(['OrderId' => $orderId]);
        $product = Baseproducts::findOne(['ProductId' => $order->ProductId]);
        $playTbl = PlayerTbl::findOne(['PlayerID' => $order->UserId]);
        $rechargeTime = $playTbl->RechargeTimes;
        $coin = $playTbl->Diamond;
        $numCount = $product->NumCount;
        if (empty($product->ClassId)){//钻石
            $beforeCurrency = $coin;
        }else{//金币
            $beforeCurrency = empty($rechargeTime) ? $coin - 10 : $playTbl->GoldCoin;
        }
        $playcurrency = new PlayerCurrencyRecordTbl();
        $playcurrency->playerId = $order->UserId;
        $playcurrency->typeId = empty($rechargeTime) ? 0 : $product->ClassId;//钻石类型为0
        $playcurrency->Currency = empty($rechargeTime) ? 10 : $numCount;
        $playcurrency->beforeCurrency = empty($rechargeTime) ? $beforeCurrency : $beforeCurrency - $numCount;
        $playcurrency->afterCurrency = empty($rechargeTime) ? $beforeCurrency + 10 : $playcurrency->beforeCurrency + $numCount;
        $playcurrency->Comments = empty($rechargeTime) ? '首充赠送钻石' : '购买商城礼包';
        $playcurrency->recordDate = date('Y-m-d H:i:s', time());
        $playcurrency->AddrIp = PubService::real_ip();
        $playcurrency->adminId = yii::$app->user->getId();
        if ($playcurrency->save()){
            return true;
        }
        return false;
    }

    /**
     * @param $orderId
     * @return bool
     * 开启额外比例和个数写入记录
     */
    public function writeExtraRecord($orderId, $count, $type)
    {
        //写入额外比例和个数赠送记录
        $order = Baseorders::findOne(['OrderId' => $orderId]);
        $product = Baseproducts::findOne(['ProductId' => $order->ProductId]);
        $playTbl = PlayerTbl::findOne(['PlayerID' => $order->UserId]);

        if (empty($product->ClassId)){
            $beforeCurrency = $playTbl->Diamond;
        }else{
            $beforeCurrency = $playTbl->GoldCoin;
        }
        $playcurrency = new PlayerCurrencyRecordTbl();
        $playcurrency->playerId = $order->UserId;
        $playcurrency->typeId = $product->ClassId;
        $playcurrency->Currency = $count;
        $playcurrency->beforeCurrency = $beforeCurrency;
        $playcurrency->afterCurrency = $playcurrency->beforeCurrency + $count;
        $playcurrency->Comments = ($type == 1) ? '购买商城礼包额外比例赠送:'.$count : '购买商城礼包额外个数赠送:'.$count;
        $playcurrency->recordDate = date('Y-m-d H:i:s', time());
        $playcurrency->AddrIp = PubService::real_ip();
        $playcurrency->adminId = 1;
        if ($playcurrency->save()){
            return true;
        }
        return false;
    }
}